

function QUI_Span(txt: string, parent: HTMLElement | null = null): HTMLSpanElement
{
    if (parent == null)
        parent = document.body;
    var span = document.createElement("span");
    span.textContent = txt;
    span.append(document.createElement("br"));
    parent.append(span);
    return span;
}
function QUI_Button(txt: string, _event: () => void, parent: HTMLElement | null = null): HTMLElement
{
    if (parent == null)
        parent = document.body;
    var btn = document.createElement("button");
    btn.textContent = txt;
    btn.onclick = _event;
    parent.append(btn);
    return btn;
}

//只有一个接口，也不用搞什么定义了，就写在这里
interface VsCodeApi
{
    postMessage(msg: any): any;
    getState(): any;
    setState(state: any): void;
}
declare function acquireVsCodeApi(): VsCodeApi;
var VsCodeApi: VsCodeApi;
function initVsCodeAPI()
{
    if (!VsCodeApi)
        VsCodeApi = acquireVsCodeApi();
}



class state
{
    count: number = 0;
}
let laststate: state;
function recvMsg(msg: MessageEvent)
{
    let type = typeof (msg.data);
    QUI_Span("==recv:" + type + "  " + msg.data);
    if (type == "object")
    {
        QUI_Span("obj=" + JSON.stringify(msg.data));
    }
}
window.onload = () =>
{
    window.onmessage = recvMsg;//从vscode 接收事件

    initVsCodeAPI();
    laststate = VsCodeApi.getState() as state;
    if (!laststate)
        laststate = new state();


    QUI_Span("hello world.");
    QUI_Button("send msg1", () =>
    {
        laststate.count++;
        VsCodeApi.setState(laststate);
        QUI_Span("send str:" + laststate.count);

        VsCodeApi.postMessage("hello world.");
    });
    QUI_Button("send msg2", () =>
    {
        laststate.count++;
        VsCodeApi.setState(laststate);
        QUI_Span("send str:" + laststate.count);

        VsCodeApi.postMessage({ "hi1": 23, "data": "ddd" });
    })

}


